/*
 * @brief:
 * @Author: TzzzT
 * @Date: 2023-02-04 13:43:17
 * @LastEditTime: 2023-05-04 22:57:33
 * @LastEditors: TzzzT
 */
#include "driver/uart.h"
#include <stdio.h>

#include "by8301.h"

#define BY_8301_TX_PIN 20
#define BY_8301_RX_PIN UART_PIN_NO_CHANGE

#define BY_8301_BAUDRATE 9600

static uart_config_t uart_config = {
    .baud_rate = BY_8301_BAUDRATE,
    .data_bits = UART_DATA_8_BITS,
    .parity = UART_PARITY_DISABLE,
    .stop_bits = UART_STOP_BITS_1,
    .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
    .source_clk = UART_SCLK_APB,
};
static const uart_port_t uart_num = UART_NUM_1;
void by8301_init(void)
{

    // Configure UART parameters
    ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
    ESP_ERROR_CHECK(uart_set_pin(uart_num, BY_8301_TX_PIN, BY_8301_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
    const int uart_buffer_size = (512);
    QueueHandle_t uart_queue;
    // Install UART driver using an event queue here
    ESP_ERROR_CHECK(uart_driver_install(uart_num, uart_buffer_size,
                                        uart_buffer_size, 10, &uart_queue, 0));
}

void by8301_send_data(char *package, uint16_t len)
{
    int length = uart_write_bytes(uart_num, package, len);
}

uint8_t XOR_bytes(uint8_t *head, uint8_t len)
{
    int i = 0;
    uint8_t sum = head[0];
    for (i = 1; i < len; i++)
    {
        sum ^= head[i];
    }
    return sum;
}

//////////////////APP//////////////////
#include "RCS_slave.h"

extern rcs_slave_system_t rcsSystem;

#define START_FLAG 0x7E
#define END_FLAG 0xEF
void play_new_song(sound_e song_sn)
{
    if (rcsSystem.device.battery > 30)
    {
        uint8_t data_array[9] = {START_FLAG, 0x05, SELECT_SONG_MP3, 0, 0, 0, END_FLAG, '\r', '\t'};
        data_array[3] = (song_sn & 0xFF00) >> 8;
        data_array[4] = (song_sn & 0x00FF);
        data_array[5] = XOR_bytes(&data_array[1], 5);
        uart_write_bytes(uart_num, data_array, 9);
    }
}
